<template>
  <div class="container">
    <el-card class="questions-card">
      <el-row :gutter="20" class="first-row">
        <el-col :span="20" class="explain-text"
          >说明：目前支持学科和关键字条件筛选</el-col
        >
        <el-col :span="4"
          ><el-button
            class="add-btn"
            type="success"
            icon="el-icon-edit"
            size="small"
            @click="
              $router.push({
                path: '/questions/new',
                query: { redirect: '/questions/list' }
              })
            "
            >新增试题</el-button
          ></el-col
        >
      </el-row>

      <el-form ref="subjectFormRef" :model="subjectForm" label-width="80px">
        <!-- 第一行选择框 -->
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="学科">
              <el-select
                v-model="subjectForm.subjectID"
                placeholder="请选择"
                size="small"
                @change="changeSubject"
                style="width:100%"
              >
                <el-option
                  v-for="item in subjects"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级目录">
              <el-select
                v-model="subjectForm.catalogID"
                placeholder="请选择"
                size="small"
                style="width:100%"
              >
                <el-option
                  v-for="item in secondDirectory"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签">
              <el-select
                v-model="subjectForm.tags"
                placeholder="请选择活动区域"
                size="small"
                style="width:100%"
              >
                <el-option
                  v-for="item in tagsList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键字">
              <el-input
                v-model.trim="subjectForm.keyword"
                placeholder="根据题干搜索"
                size="small"
                style="width:100%"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行选择框 -->
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="试题类型">
              <el-select
                v-model="subjectForm.questionType"
                placeholder="请选择"
                size="small"
                style="width:100%"
              >
                <el-option
                  v-for="item in questionTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="难度">
              <el-select
                v-model="subjectForm.difficulty"
                placeholder="请选择"
                size="small"
                style="width:100%"
              >
                <el-option
                  v-for="item in difficultyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方向">
              <el-select
                v-model="subjectForm.direction"
                placeholder="请选择"
                size="small"
                style="width:100%"
              >
                <el-option
                  v-for="(item, index) in directionList"
                  :key="index"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入人">
              <el-select
                v-model="subjectForm.creatorID"
                placeholder="请选择"
                size="small"
                style="width:100%"
              >
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行选择框 -->
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="题目备注">
              <el-input
                v-model.trim="subjectForm.remarks"
                size="small"
                style="width:100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业简称">
              <el-input
                v-model.trim="subjectForm.shortName"
                size="small"
                style="width:100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="城市">
              <el-select
                v-model="subjectForm.province"
                placeholder="请选择"
                style="width:49%;margin-right:2%"
                size="small"
                @change="changeProvince"
              >
                <el-option
                  v-for="(item, index) in provinces"
                  :key="index"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
              <el-select
                v-model="subjectForm.city"
                placeholder="请选择"
                style="width:49%"
                size="small"
              >
                <el-option
                  v-for="(item, index) in citys"
                  :key="index"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="search-btns">
              <el-button size="small" @click="clearSelectedHistory"
                >清除</el-button
              >
              <el-button type="primary" size="small" @click="getQuestions"
                >搜索</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 警告栏 -->
      <el-alert
        :title="`数据一共 ${total} 条`"
        type="info"
        class="alert-infomation"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 表格 -->
      <el-table :data="questionTableData">
        <el-table-column prop="number" label="试题编号" width="120">
        </el-table-column>
        <el-table-column prop="subject" label="学科"> </el-table-column>
        <el-table-column prop="catalog" label="目录"> </el-table-column>
        <el-table-column prop="questionType" label="题型">
          <template slot-scope="scope">
            {{ questionTypeList[scope.row.questionType - 1].label }}
          </template>
        </el-table-column>
        <el-table-column prop="question" label="题干" width="280">
          <template slot-scope="scope">
            <span v-html="scope.row.question"></span>
          </template>
        </el-table-column>
        <el-table-column prop="addDate" label="录入时间" width="180">
          <template slot-scope="scope">{{
            scope.row.addDate | dateFormat
          }}</template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度">
          <template slot-scope="scope">
            {{ difficultyList[scope.row.difficulty - 1].label }}
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="录入人"> </el-table-column>
        <el-table-column prop="" label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-view"
              circle
              plain
              size="small"
              @click="questionsPreview(scope.row.id)"
            ></el-button>
            <el-button
              type="success"
              icon="el-icon-edit"
              plain
              size="small"
              circle
              @click="
                $router.push({
                  path: '/questions/new',
                  query: { id: scope.row.id, redirect: '/questions/list' }
                })
              "
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              plain
              circle
              @click="deleteQuestion(scope.row)"
              size="small"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-check"
              plain
              size="small"
              circle
              @click="addQuestionChoice(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        class="pagination-table"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 20, 30, 50]"
        :page-size="pagesize"
        layout=" prev, pager, next, sizes,jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>

    <!-- 题目预览 -->
    <el-dialog
      title="题目预览"
      :visible.sync="isQuestionsPreviewDialogVisible"
      width="45%"
      v-if="isQuestionsPreviewDialogVisible"
      @close="previewId = 0"
    >
      <questions-preview :id="previewId" />
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="isQuestionsPreviewDialogVisible = false"
          >关 闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import QuestionsPreview from '../components/questions-preview'
import { simple as simpleSubjects } from '@/api/hmmm/subjects'
import { simple as simpleDirectorys } from '@/api/hmmm/directorys'
import {
  list as questionList,
  remove as removeQuestion,
  choiceAdd
} from '@/api/hmmm/questions'
import { simple as simpleTags } from '@/api/hmmm/tags'
import { provinces, citys } from '@/api/hmmm/citys'
import { simple as simpleUsers } from '@/api/base/users'
import { questionType, difficulty, direction } from '@/api/hmmm/constants'
export default {
  name: 'Questions',
  components: { QuestionsPreview },
  props: {},
  data() {
    return {
      subjectForm: {
        subjectID: null,
        difficulty: null,
        questionType: null,
        tags: null,
        province: null,
        city: null,
        keyword: null, // 关键字
        remarks: null, // 题目备注
        shortName: null, // 企业简称
        direction: null,
        creatorID: null,
        catalogID: null
      }, // 表单数据收集
      // ##1
      subjects: [], // 学科列表
      // ##2
      secondDirectory: [],
      // ##3
      tagsList: [],
      // ##4 试题类型
      questionTypeList: questionType,
      // ##5 难度
      difficultyList: difficulty,
      // ##6 方向
      directionList: direction,
      // ##7 录入人
      users: [],
      // ##8 城市
      provinces: [],
      citys: [],
      // 查询页码和条数
      total: 0,
      page: 1,
      pagesize: 5,
      questionTableData: [], // 表格数据
      // 预览窗口控制
      isQuestionsPreviewDialogVisible: false,
      previewId: 0
    }
  },
  created() {
    this.getSimpleSubjects()
    this.getUsers()
    // #8 获取城市
    this.provinces = provinces()
    this.getQuestions()
  },
  mounted() {},
  methods: {
    // #1 学科简单列表
    async getSimpleSubjects() {
      try {
        const { data } = await simpleSubjects()
        this.subjects = data
      } catch (err) {
        this.$message.error('获取学科列表失败')
      }
    },
    async changeSubject(val) {
      // 当学科选择改变，需要清空上一次选择的尸体
      this.secondDirectory = []
      this.subjectForm.catalogID = null
      this.tagsList = []
      this.subjectForm.tags = null
      this.getSecondDirectory(val)
      this.getTags(val)
    },
    // #2 获取二级目录
    async getSecondDirectory(val) {
      try {
        const { data } = await simpleDirectorys({
          subjectID: val
        })
        this.secondDirectory = data
        // console.log(data)
      } catch (err) {
        this.$message.error('获取二级目录失败')
      }
    },
    // #3 获取标签列表
    async getTags(val) {
      try {
        const { data } = await simpleTags({
          subjectID: val
        })
        this.tagsList = data
      } catch (err) {
        this.$message.error('获取二级目录失败')
      }
    },
    // #7 获取用户
    async getUsers() {
      try {
        const { data } = await simpleUsers()
        this.users = data
      } catch (err) {
        this.$message.error('获取录取人列表失败')
      }
    },
    // 改变省份则请求城市区域
    changeProvince(val) {
      this.citys = []
      this.subjectForm.city = null
      this.citys = citys(val)
    },
    // #9 清空历史选择
    clearSelectedHistory() {
      for (const k in this.subjectForm) {
        this.subjectForm[k] = null
      }
      this.citys = []
      this.secondDirectory = []
      this.tagsList = []
      this.getQuestions()
      // this.$refs.subjectFormRef.resetFields() // ! 必须有prop才能使用这个
    },
    // #10 获取查询的表格数据
    async getQuestions() {
      try {
        const {
          data: { items, counts }
        } = await questionList({
          page: this.page,
          pagesize: this.pagesize,
          ...this.subjectForm
        })
        this.total = counts
        this.questionTableData = items
      } catch (err) {
        this.$message.error('获取学科列表失败')
      }
    },
    // 查询条数改变
    handleSizeChange(newPageSize) {
      this.pagesize = newPageSize
      this.getQuestions()
    },
    // 查询页码改变
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getQuestions()
    },
    // #11 删除题目
    async deleteQuestion(row) {
      const confirmStr = await this.$confirm(
        '此操作将永久删除该题目, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmStr !== 'confirm') return
      try {
        await removeQuestion(row)
        this.$message.success('删除成功')
        // 处理页码变换小bug
        if (this.questionTableData.length === 1) {
          this.page = this.page === 1 ? 1 : this.page - 1
        }
        this.getQuestions()
      } catch (err) {
        this.$message.error('删除失败')
      }
    },
    // #12 加入精选
    async addQuestionChoice(id) {
      const confirmStr = await this.$confirm(
        '此操作将该题目加入精选, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).catch(err => err)
      if (confirmStr !== 'confirm') return
      try {
        await choiceAdd({
          id,
          choiceState: 1
        })
        this.$message.success('加入精选成功')
        this.getQuestions()
      } catch (err) {
        this.$message.error('加入精选失败')
      }
    },
    // #13  题目预览
    questionsPreview(id) {
      this.previewId = id
      this.isQuestionsPreviewDialogVisible = true
    }
  },
  computed: {},
  watch: {}
}
</script>

<style scoped lang="less">
.container {
  padding: 10px;
}
.first-row {
  margin-bottom: 15px;
}
.explain-text {
  font-size: 12px;
  color: pink;
}
.add-btn {
  float: right;
}
.search-btns {
  text-align: right;
}
.alert-infomation {
  margin-bottom: 15px;
}
.pagination-table {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
/deep/.el-pagination__jump {
  margin-left: unset;
}
/deep/.el-dialog__footer {
  display: flex;
  justify-content: flex-end;
}
</style>
